package com.gome.ocean.service.utils.job.writer;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.gome.ocean.common.constants.Constants;
import com.gome.ocean.service.utils.job.CreateJobUtils;
import com.google.common.collect.Maps;

/**
 * Created by liuqingxia on 2016/2/1.
 */
public class MongoDBWriter {

    public static final String   formatErrorMsg = "writer的参数columns格式不规范，正确格式：name1=type1，name2=type2,...";
    public static final String[] MAP_KEYS       = new String[] { "address", "userName", "userPassword", "dbName",
                                                                 "collectionName", "columns" };

    public static Map<String, Object> getWriterMap(HttpServletRequest req) {
        Map<String, Object> writerMaps = Maps.newHashMap();
        for (String key : MAP_KEYS) {
            String paramName = CreateJobUtils.addPrefix(Constants.REQUEST_WRITER_PARAM_PRE, key);
            String paramValue = req.getParameter(paramName);
            if (StringUtils.isBlank(paramValue)) {
                throw new IllegalArgumentException("参数" + paramName + "不能为空");
            }
            if ("columns".equals(key)) {
                String[] kvs = paramValue.split(Constants.REG_CN_OR_EN_COMMA);
                Map<String, String> kvMap = Maps.newLinkedHashMap();
                ;
                for (String kv : kvs) {
                    if (!kv.contains("=")) {
                        throw new IllegalArgumentException(formatErrorMsg);
                    }
                    String[] kvArr = kv.split("=");
                    if (kvArr.length != 2) {
                        throw new IllegalArgumentException(formatErrorMsg);
                    }
                    kvMap.put(kvArr[0], kvArr[1]);
                }
                writerMaps.put(key, kvMap);
                continue;
            }
            writerMaps.put(key, paramValue);
        }
        return writerMaps;
    }
}
